package com.yanghui.lingyue.functions.python

import com.icedata.sika.bridge.SikaEvent
import com.icedata.sika.bridge.SikaGroupEvent
import com.icedata.sika.bridge.SikaPlainMessage
import com.icedata.sika.bridge.SikaUserEvent
import com.icedata.sika.core.CommandProcessor
import com.icedata.sika.core.Sika
import com.yanghui.lingyue.data.Command
import com.yanghui.lingyue.functions.AbstractFunction
import com.yanghui.lingyue.utils.functionUtils.FunctionUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.*

@Suppress("BlockingMethodInNonBlockingContext")
object BalanceChemistry : AbstractFunction() {
    override val name = "Balance"

    override suspend fun parse(event: SikaEvent, sika: Sika): LinkedList<Command> {
        val command = LinkedList<Command>()
        if (event is SikaUserEvent) return command
        event as SikaGroupEvent
        if (event.sendGroup.id !in enableGroup) return command

        val param = FunctionUtils.extractKeyword(event, "配平")
        param?.let {
            command.add(Command(event, name, it))
        }
        return command
    }

    override suspend fun execute(command: Command, sika: Sika): CommandProcessor.Result {
        val param = command.param
        if (param == "--help") {
            command.sendGroup?.sendMessage("运行格式：\n@Bot(空格)配平(空格)方程式\n方程式可以是直接用等号连接，也可以用分号进行模糊匹配，如H2;O2;H2O，元素符号必须要保证正确")
        }
        val builder = StringBuilder()
        withContext(Dispatchers.IO) {
            val rt = Runtime.getRuntime()
            val pr = rt.exec("python -u C:\\LingYue\\Balance.py $param")
            val input = BufferedReader(InputStreamReader(pr.inputStream, "GBK"))
            var line: String?
            while (input.readLine().also { line = it } != null) {
                builder.append(line)
            }
        }
        command.sendGroup?.sendMessage(builder.toString())
        return CommandProcessor.Result.ADOPT
    }

    override fun filter(command: Command): Boolean {
        return command.instruction.startsWith(name)
    }
}